<template>
  <div>
<!--    面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片视图-->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input placeholder="请输入内容" clearable @clear="getUserList" v-model="queryInfo.query" @keyup.native.enter="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
<!--    用户类表-->
    <el-table :data="userList" border stripe>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="stateChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUserById(scope.row.id)"></el-button>
          <el-tooltip content="分配角色" placement="top" effect="dark" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
<!--    分页处理-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 8]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total=total>
    </el-pagination>
<!--    新增用户对话框-->
    <el-dialog
      title="新增用户"
      :visible.sync="addDialogVisible"
      @close="dialogClose('addFormRef')"
      width="50%">
      <!--主体区域-->
      <el-form :model="userForm" :rules="userFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="userSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!--    修改用户对话框-->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      @close="dialogClose('editFormRef')"
      width="50%">
      <!--主体区域-->
      <el-form :model="userForm" :rules="userFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!--    分配权限对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="setRoleDialogVisible"
      @close="setRoleDialogClose"
      width="50%">
      <!--主体区域-->
      <div>
        <p>当前的用户: {{userInfo.username}}</p>
        <p>当前的角色: {{userInfo.role_name}}</p>
        <p>分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>

      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/
      if (regEmail.test(value)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    // 验证手机号的规则
    const checkMobie = (rule, value, cb) => {
      const regMobie = /^1(3|4|5|7|8)\d{9}$/
      if (regMobie.test(value)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      // 控制添加对话框的显示和隐藏
      addDialogVisible: false,
      // 添加用户表单数据
      userForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单的规则对象
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobie, trigger: 'blur' }
        ]
      },
      // 修改用户对话框显示和隐藏
      editDialogVisible: false,
      // 分配用户对话框显示和隐藏
      setRoleDialogVisible: false,
      // 需要分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      roleList: [],
      // 选中的角色ID值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()

  },
  methods: {
    // 关闭分配角色对话框
    setRoleDialogClose() {
      this.selectedRoleId = ''
      this.userInfo = []
    },
    // 点击按钮分配权限
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$msg.error('请选择一个角色')
      }
      const res = await this.$http.put(`users/${this.userInfo.id}/role`, {
        id: this.userInfo.id,
        rid: this.selectedRoleId
      })
      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }
      // this.userList.
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 分配角色的单击事件
    async setRole(user) {
      this.userInfo = user
      // 在展示对话框之前获取所有角色列表
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    // 删除用户
    async deleteUserById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确认'confirm' 取消 'cancel'
      if (confirmResult != 'confirm') {
        return this.$msg.info('取消了删除')
      }
      const res = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }
      this.$msg.success(res.meta.msg)
      this.getUserList()
    },
    // 修改按钮的单击事件
    showEditDialog(user) {
      Object.assign(this.userForm, user)
      this.editDialogVisible = true
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        // 通过校验可以发起提交请求
        const res = await this.$http.put('users/' + this.userForm.id,
          { email: this.userForm.email, mobile: this.userForm.mobile })
        if (res.meta.status !== 200) {
          return this.$msg.error(res.meta.msg)
        }
        this.$msg.success(res.meta.msg)
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    userSubmit() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        // 通过校验可以发起提交请求
        const res = await this.$http.post('users', this.userForm)
        if (res.meta.status !== 201) {
          return this.$msg.error(res.meta.msg)
        }
        this.$msg.success(res.meta.msg)
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 监听对话框的关闭事件
    dialogClose(formRefName) {
      this.$refs[formRefName].resetFields()
    },
    // 监听pagesize改变得事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变得事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async getUserList() {
      const res = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(this.userList)
    },
    // 监听switch开关状态的改变
    async stateChange(user) {
      const res = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        return this.$msg.error(res.meta.msg)
      }
      this.$msg.success(res.meta.msg)
    }

  }
}
</script>

<style scoped>

</style>
